/* 
 * Copyright 2011-2012 Andrew Brock
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.catchwa.myvideobrowser.gui;

import java.awt.Component;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Arrays;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableRowSorter;
import org.catchwa.myvideobrowser.model.AlternateMatch;
import org.catchwa.myvideobrowser.Main;
import org.catchwa.myvideobrowser.MoviePopulator;
import org.catchwa.myvideobrowser.model.Movie;

/**
 *
 * @author Andrew Brock
 */
public class Browser extends JFrame {

  private JMenuBar menuBar;
  private JMenu fileMenu;
  private JMenu helpMenu;
  private JMenuItem selectRootDirectoryMenuItem;
  private JMenuItem videoFileExtensionsMenuItem;
  private JMenuItem exitMenuItem;
  private JMenuItem aboutMenuItem;
  private JSplitPane splitPane;
  private JTable videoTable;
  private MovieTableModel tableModel;
  private JScrollPane tableScrollPane;
  private MovieInfoPanel infoPanel;

  public Browser() {
    super("My Video Browser");
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    Image icon = toolkit.createImage("images/Logo.png");
    setIconImage(icon);
    setSize(1100, 900);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    menuBar = new JMenuBar();
    fileMenu = new JMenu("File");
    helpMenu = new JMenu("Help");
    selectRootDirectoryMenuItem = new JMenuItem("Select root movie directory");
    selectRootDirectoryMenuItem.addActionListener(new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent e) {
       SwingUtilities.invokeLater(new Runnable() {
          @Override
            public void run() {
        boolean chosen = Main.displayRootDirectoryChooser();
        if(chosen) {
          MoviePopulator mp = new MoviePopulator();
          mp.execute();
            }
          }});
      }});
    videoFileExtensionsMenuItem = new JMenuItem("Configure Video File Extensions...");
    videoFileExtensionsMenuItem.addActionListener(new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent e) {
        new VideoExtensionsDialog();
      }
    });
    exitMenuItem = new JMenuItem("Exit");
    exitMenuItem.addActionListener(new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent e) {
        System.exit(0);
      }
    });
    aboutMenuItem = new JMenuItem("About...");
    aboutMenuItem.addActionListener(new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent e) {
        new AboutDialog();
      }
    });
    fileMenu.add(selectRootDirectoryMenuItem);
    fileMenu.add(videoFileExtensionsMenuItem);
    fileMenu.add(exitMenuItem);
    helpMenu.add(aboutMenuItem);
    menuBar.add(fileMenu);
    menuBar.add(helpMenu);
    setJMenuBar(menuBar);
    splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
    tableModel = new MovieTableModel();
    videoTable = new JTable(tableModel);
    videoTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    videoTable.setRowSorter(new TableRowSorter(tableModel));
    videoTable.getColumnModel().getColumn(0).setPreferredWidth(200);
    videoTable.getColumn("Runtime").setCellRenderer(new DefaultTableCellRenderer() {
      @Override
      public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        Integer runtime = (Integer) value;
        return super.getTableCellRendererComponent(table, runtime.intValue() + " mins", isSelected, hasFocus, row, column);
      }
    });
    tableScrollPane = new JScrollPane(videoTable);
    splitPane.add(tableScrollPane);
    infoPanel = new MovieInfoPanel(videoTable);
    videoTable.getSelectionModel().addListSelectionListener(infoPanel);
    videoTable.addMouseListener(new MouseAdapter() {
     
      @Override
      public void mouseClicked(MouseEvent e) {
        if (e.getClickCount() == 2) {
          JTable source = (JTable) e.getSource();
          int viewRow = source.rowAtPoint(e.getPoint());
          int viewCol = source.columnAtPoint(e.getPoint());
          final int modelRow = source.convertRowIndexToModel(viewRow);
          if (!source.isRowSelected(viewRow)) {
            source.changeSelection(viewRow, viewCol, false, false);
          }
          if (Arrays.asList(MovieTableModel.columns).indexOf("Watched") != videoTable.convertColumnIndexToModel(viewCol))
          {
            SwingUtilities.invokeLater(Main.createOpenMovieThread(tableModel.getMovie(modelRow)));
          }
        }
      }

      @Override
      public void mouseReleased(MouseEvent e) {
        if (e.isPopupTrigger()) {
          JTable source = (JTable) e.getSource();
          int viewRow = source.rowAtPoint(e.getPoint());
          int viewCol = source.columnAtPoint(e.getPoint());
          final int modelRow = source.convertRowIndexToModel(viewRow);
          if (!source.isRowSelected(viewRow)) {
            source.changeSelection(viewRow, viewCol, false, false);
          }
          JPopupMenu popup = new JPopupMenu();
          JMenuItem open = new JMenuItem("Open");
          open.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
              SwingUtilities.invokeLater(Main.createOpenMovieThread(tableModel.getMovie(modelRow)));
            }
          });
          popup.add(open);
          if(tableModel.getMovie(modelRow).getAlternateMatches().length > 0) {
            JMenu alternateMatchesMenu = new JMenu("Alternate Matches");
            AlternateMatch[] alternateMatches = tableModel.getMovie(modelRow).getAlternateMatches();
            for(final AlternateMatch am : alternateMatches) {
              JMenuItem alternateMatch = new JMenuItem(am.getTitle()+" ("+am.getReleasedYear()+")");
              alternateMatch.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                  SwingUtilities.invokeLater(Main.createSwitchMovieThread(tableModel.getMovie(modelRow), am));
                }
              });
              alternateMatchesMenu.add(alternateMatch);
            }
            popup.add(alternateMatchesMenu);
          }
          popup.show(e.getComponent(), e.getX(), e.getY());
        }
      }
    });
    splitPane.add(infoPanel);
    splitPane.setDividerLocation(520);
    add(splitPane);
    setVisible(true);
  }

  public void addMovieToTable(Movie m) {
    tableModel.add(m);
  }

  public void removeMovieFromTable(Movie m) {
    tableModel.remove(m);
  }
  
  public void removeAllMoviesFromTable() {
    tableModel.removeAll();
  }
  
  public void clearSelection() {
    videoTable.clearSelection();
    infoPanel.clear();
  }
}
